﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Activation;
using Microsoft.SharePoint;

namespace Learn.SharePoint.com
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class LastViewedService : ILastViewedService
    {
        public string GetLastViewed(string listId, string ids)
        {
            string returnValue = "";
            SPList list = SPContext.Current.Web.Lists[new Guid(listId)];
            var idsArray = ids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string id in idsArray)
            {
                SPListItem item = list.GetItemById(int.Parse(id));

                var query = new SPAuditQuery(SPContext.Current.Site);
                query.AddEventRestriction(SPAuditEventType.View);
                query.RestrictToListItem(item);
                var entries = list.Audit.GetEntries(query);
                if (entries.Count > 0)
                {
                    returnValue += TimeZoneInfo.ConvertTimeFromUtc(entries[entries.Count - 1].Occurred, TimeZoneInfo.Local).ToString() + ",";
                }
                else
                {
                    returnValue += "Never,";
                }
            }
            return returnValue;
        }

        public bool Refresh(string listId)
        {
            bool returnValue = false;
            var spcontext = SPContext.Current;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var site = new SPSite(spcontext.Site.ID))
                {
                    using (var web = site.AllWebs[spcontext.Web.ID])
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists[new Guid(listId)];
                        LastViewedField field = null;
                        foreach (SPField listField in list.Fields)
                        {
                            if (listField.TypeAsString == "LastViewedField")
                            {
                                field = (LastViewedField)listField;
                                break;
                            }
                        }
                        if (field != null)
                        {
                            var query = new SPQuery();
                            query.Query = @"<Where><IsNull><FieldRef Name=" + field.InternalName + @"/></IsNull></Where>";
                            var itemsToUpdate = list.GetItems(query);
                            if (itemsToUpdate.Count > 0)
                            {
                                foreach (SPListItem item in itemsToUpdate)
                                {
                                    var auditQuery = new SPAuditQuery(SPContext.Current.Site);
                                    auditQuery.AddEventRestriction(SPAuditEventType.View);
                                    auditQuery.RestrictToListItem(item);
                                    var entries = list.Audit.GetEntries(auditQuery);
                                    if (entries.Count > 0)
                                    {
                                        item[field.Id] = TimeZoneInfo.ConvertTimeFromUtc(entries[entries.Count - 1].Occurred, TimeZoneInfo.Local).ToString() + "," + item.ID;
                                    }
                                    else
                                    {
                                        item[field.Id] = "Never," + item.ID;
                                    }                                    
                                    item.SystemUpdate(false);
                                }
                                returnValue = true;
                            }
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
            return returnValue;
        }
    }
}
